﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SHW_UP.UI;
using SHW_UP.BP;
using System.Threading;
namespace SHW_UP
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        public static string comPort = string.Empty;

        private void frmMain_Load(object sender, EventArgs e)
        {
            this.timerLabel.Text = DateTime.Now.ToString();
            this.statusLabel.Text = "Welcome";
            this.timer1.Interval = 1000;
            this.timer1.Start();
            frmWelcome frmwelcome = new frmWelcome();
            frmwelcome.MdiParent = this;
            frmwelcome.WindowState = FormWindowState.Maximized;
            frmwelcome.ControlBox = false;
            frmwelcome.Show();
            operMenu(false);
            operToolBar(false);
        }

        private void operMenu(bool flag)
        {
            this.serialPortCloseSet.Enabled = flag;
            this.serialPortWriteSet.Enabled = flag;
            this.serialPortReadSet.Enabled = flag;
            this.expParSet.Enabled = flag;
            this.impParSet.Enabled = flag;
        }

        private void operToolBar(bool flag)
        {
            this.mobileBtn.Enabled = flag;
            this.passwdBtn.Enabled = flag;
            this.GPRSBtn.Enabled = flag;
            this.controlBtn.Enabled = flag;
            this.timeZoneBtn.Enabled = flag;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.timerLabel.Text = DateTime.Now.ToString();
        }

        frmMobile frmmobile = null;
        private void mobileBtn_Click(object sender, EventArgs e)
        {
            if (frmmobile == null)
            {
                frmmobile = new frmMobile();
                frmmobile.MdiParent = this;
                frmmobile.WindowState = FormWindowState.Maximized;
                frmmobile.ControlBox = false;
                frmmobile.Show();
            }
            else
            {
                frmmobile.Activate();
            }
            
        }

        frmPasswd frmpasswd = null;
        private void passwdBtn_Click(object sender, EventArgs e)
        {
            if (frmpasswd == null)
            {
                frmpasswd = new frmPasswd();
                frmpasswd.MdiParent = this;
                frmpasswd.WindowState = FormWindowState.Maximized;
                frmpasswd.ControlBox = false;
                frmpasswd.Show();
            }
            else 
            {
                frmpasswd.Activate();
            }
        }

        frmSelectPort frmselectport = null;
        private void serialPortSet_Click(object sender, EventArgs e)
        {       frmselectport = new frmSelectPort();
                //frmselectport.MdiParent = this;
                //frmselectport.WindowState = FormWindowState.Maximized;
                frmselectport.ControlBox = false;
                frmselectport.ShowDialog();
        }

        frmGPRS frmgprs = null;
        private void GPRSBtn_Click(object sender, EventArgs e)
        {
            if (frmgprs == null)
            {
                frmgprs = new frmGPRS();
                frmgprs.MdiParent = this;
                frmgprs.WindowState = FormWindowState.Maximized;
                frmgprs.ControlBox = false;
                frmgprs.Show();
            }
            else
            {
                frmgprs.Activate();
            }
        }

        frmControl frmcontrol = null;
        private void controlBtn_Click(object sender, EventArgs e)
        {
            if (frmcontrol == null)
            {
                frmcontrol = new frmControl();
                frmcontrol.MdiParent = this;
                frmcontrol.WindowState = FormWindowState.Maximized;
                frmcontrol.ControlBox = false;
                frmcontrol.Show();
            }
            else
            {
                frmcontrol.Activate();
            }
        }

        frmTimeZone frmtimezone = null;
        private void timeZoneBtn_Click(object sender, EventArgs e)
        {
            if (frmtimezone == null)
            {
                frmtimezone = new frmTimeZone();
                frmtimezone.MdiParent = this;
                frmtimezone.WindowState = FormWindowState.Maximized;
                frmtimezone.ControlBox = false;
                frmtimezone.Show();
            }
            else
            {
                frmtimezone.Activate();
            }
        }

        private void exitAppSet_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void serialPortOpenSet_Click(object sender, EventArgs e)
        {
            if (comPort == string.Empty)
            {
                MessageBox.Show("请选择连接的端口");
            }
            else
            {
                try
                {
                    this.serialPort1.PortName = comPort;
                    this.serialPort1.BaudRate = 9600;
                    this.serialPort1.ReadBufferSize = 1024;
                    this.serialPort1.WriteBufferSize = 1024;
                    this.serialPort1.Open();
                   //threadFlag = true;
                   // _readThread = new Thread(readSerialPort);
                   // _readThread.Start();
                    operMenu(true);
                    //operToolBar(true);
                    //sendHexInfo("5468");
                    string passwd = string.Empty;
                    if (InfoUtils.parTable.Contains("passwd"))
                    {
                        passwd = (string)InfoUtils.parTable["passwd"];
                    }
                    else
                    {
                        passwd = "000000";
                    }
                    sendStrInfo("CXSZ," + passwd + ",");
                }
                catch (Exception exce)
                {
                    MessageBox.Show(exce.Message);
                }
            }
        }

        private void sendStrInfo(string info)
        {
            byte[] data = InfoUtils.GetXORFull(Encoding.Default.GetBytes(info));
            //string str = Convert.ToBase64String(data);
            serialPort1.Write(data, 0, data.Length);
            //serialPort1.WriteLine(info);
        }

        private void sendHexInfo(string info)
        {
            byte[] data =InfoUtils.GetXORFull(InfoUtils.strToHexByte(info));
            serialPort1.Write(data, 0, data.Length);
        }
       
        private void serialPortCloseSet_Click(object sender, EventArgs e)
        {
            try
            {
                this.serialPort1.Dispose();
                this.serialPort1.Close();
                //threadFlag = false;
                //_readThread.Abort();
                operMenu(false);
                operToolBar(false);
                if (frmmobile != null)
                {
                    frmmobile.Close();
                    frmmobile = null;
                }
                if (frmpasswd != null)
                {
                    frmpasswd.Close();
                    frmpasswd = null;
                }
                if (frmgprs != null)
                {
                    frmgprs.Close();
                    frmgprs = null;
                }
                if (frmcontrol != null)
                {
                    frmcontrol.Close();
                    frmcontrol = null;
                }
                if (frmtimezone != null)
                {
                    frmtimezone.Close();
                    frmtimezone = null;
                }
            }
            catch (Exception exe)
            {
                MessageBox.Show(exe.Message);
            }
        }
        delegate void SetTerminalStatusTextCallback(string str);   //定义委托
        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            byte[] byteBuffer = new byte[this.serialPort1.ReadBufferSize];
            int count = this.serialPort1.Read(byteBuffer, 0, byteBuffer.Length);
             if (count != 0)
             {
                 if (count <= 5 && count > 3)
                 {
                     string hexstr = InfoUtils.byteToHexStr(byteBuffer);
                     if (hexstr.Equals("5468038023"))
                     {
                         setInfoToText("设置成功");
                     }
                     else if (hexstr.Equals("5468030823"))
                     {

                     }
                     else if (hexstr.Equals("5468031123"))
                     {
                         setInfoToText("密码错误");
                     }
                     else if (hexstr.Equals("5468028023"))
                     {
                         setInfoToText("进入参数修改模式");
                     }
                 }
                 else
                 {
                     string serialInfo = Encoding.Default.GetString(byteBuffer, 0, count);
                     setInfoToText(serialInfo);
                     if (count >= 200)
                     {
                         string[] termianlPar=serialInfo.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                         List<string> mobileList = new List<string>();
                         for (int i = 0; i < termianlPar.Length; i++)
                         {
                             switch (i)
                             {
                                 case 0:
                                     break;
                                 case 1:
                                     break;
                                 case 2:
                                     if (InfoUtils.parTable.ContainsKey("mode"))
                                     {
                                         InfoUtils.parTable.Remove("mode");
                                     }
                                     InfoUtils.parTable.Add("mode", termianlPar[i].Substring(termianlPar[i].IndexOf(":")+1).Trim());
                                     break;
                                 case 3:
                                     if (InfoUtils.parTable.ContainsKey("tid"))
                                     {
                                         InfoUtils.parTable.Remove("tid");
                                     }
                                     InfoUtils.parTable.Add("tid", termianlPar[i].Substring(termianlPar[i].IndexOf(":") + 1).Trim());
                                     break;
                                 case 4:
                                     if (InfoUtils.parTable.ContainsKey("gprstime"))
                                     {
                                         InfoUtils.parTable.Remove("gprstime");
                                         InfoUtils.parTable.Remove("tcp");
                                     }
                                     InfoUtils.parTable.Add("tcp","TCP");
                                     InfoUtils.parTable.Add("gprstime", termianlPar[i].Substring(termianlPar[i].IndexOf(":") + 1).Trim());
                                     break;
                                 case 5:
                                     if (InfoUtils.parTable.ContainsKey("gpstime"))
                                     {
                                         InfoUtils.parTable.Remove("gpstime");
                                     }
                                     InfoUtils.parTable.Add("gpstime", termianlPar[i].Substring(termianlPar[i].IndexOf(":") + 1).Trim());
                                     break;
                                 case 6:
                                     if (InfoUtils.parTable.ContainsKey("timezone"))
                                     {
                                         InfoUtils.parTable.Remove("timezone");
                                         InfoUtils.parTable.Remove("gmt");
                                     }
                                     string timestr = termianlPar[i].Trim().Substring(3);
                                     InfoUtils.parTable.Add("timezone", timestr.Substring(0, 1));
                                     InfoUtils.parTable.Add("gmt", timestr.Substring(1, 1));
                                     break;
                                 case 7:
                                     if (InfoUtils.parTable.ContainsKey("apn"))
                                     {
                                         InfoUtils.parTable.Remove("apn");
                                     }
                                     InfoUtils.parTable.Add("apn", termianlPar[i].Substring(termianlPar[i].IndexOf(":") + 1).Trim());
                                     break;
                                 case 8:
                                     if (InfoUtils.parTable.ContainsKey("apnusername"))
                                     {
                                         InfoUtils.parTable.Remove("apnusername");
                                     }
                                     InfoUtils.parTable.Add("apnusername", termianlPar[i].Substring(termianlPar[i].IndexOf(":") + 1).Trim());
                                     break;
                                 case 9:
                                     if (InfoUtils.parTable.ContainsKey("apnpasswd"))
                                     {
                                         InfoUtils.parTable.Remove("apnpasswd");
                                     }
                                     InfoUtils.parTable.Add("apnpasswd", termianlPar[i].Substring(termianlPar[i].IndexOf(":") + 1).Trim());
                                     break;
                                 case 10:
                                     if (InfoUtils.parTable.ContainsKey("ip"))
                                     {
                                         InfoUtils.parTable.Remove("ip");
                                     }
                                     InfoUtils.parTable.Add("ip", termianlPar[i].Substring(termianlPar[i].IndexOf(":") + 1).Trim());
                                     break;
                                 case 11:
                                     if (InfoUtils.parTable.ContainsKey("port"))
                                     {
                                         InfoUtils.parTable.Remove("port");
                                     }
                                     InfoUtils.parTable.Add("port", termianlPar[i].Substring(termianlPar[i].IndexOf(":") + 1).Trim());
                                     break;
                             }
                             if (i > 11)
                             {
                                 mobileList.Add(termianlPar[i].Substring(termianlPar[i].IndexOf(":") + 1).Trim());
                             }
                         }
                         if (InfoUtils.parTable.ContainsKey("mobile"))
                         {
                             InfoUtils.parTable.Remove("mobile");
                         }
                             InfoUtils.parTable.Add("mobile", mobileList);
                             operToolBar(true);
                     }
                 }

                
             }
              
        }

        private void setInfoToText(string strinfo)
        {
            if (teriminalStatusText.InvokeRequired)
            {
                SetTerminalStatusTextCallback setInfoCallback = new SetTerminalStatusTextCallback(setInfoToText);   //实例化委托对象
                teriminalStatusText.Invoke(setInfoCallback, strinfo);   //重新调用SetListBox函数
            }
            else 
            {
                if (strinfo.Length > 200)
                    operToolBar(true);
                this.teriminalStatusText.AppendText(strinfo);
                    
            }
           
        }


        private void readSerialPort()
        {
            while (threadFlag)
            {
                if (this.serialPort1.IsOpen)
                {

                    byte[] byteBuffer = new byte[this.serialPort1.ReadBufferSize];
                    int count = this.serialPort1.Read(byteBuffer, 0, byteBuffer.Length);    
                    if (count != 0)
                    {
                        string serialInfo = Encoding.Default.GetString(byteBuffer, 0, count);
                        MessageBox.Show(serialInfo);
                    }
                }
                else 
                {
                    Thread.Sleep(1000);
                }
            }
        }
        //Thread _readThread=null;
        bool threadFlag = false;

        private void expParSet_Click(object sender, EventArgs e)
        {

        }

        private void serialPortWriteSet_Click(object sender, EventArgs e)
        {
            if (InfoUtils.sendInfoTable.Count <= 0)
            {
                MessageBox.Show("请修改相对应的参数后，再写入。");
                return;
            }
            sendHexInfo("5468020123");
            
            if (InfoUtils.sendInfoTable.Contains("XGYHMM"))
            {
                this.teriminalStatusText.AppendText("设置密码");
                sendStrInfo((string)InfoUtils.sendInfoTable["XGYHMM"]);
                InfoUtils.sendInfoTable.Remove("XGYHMM");
            }
           
            if (InfoUtils.sendInfoTable.Contains("GPRS"))
            {
                this.teriminalStatusText.AppendText("设置GPRS参数");
                sendStrInfo((string)InfoUtils.sendInfoTable["GPRS"]);
                InfoUtils.sendInfoTable.Remove("GPRS");
            }
           
            if (InfoUtils.sendInfoTable.Contains("SQTZ"))
            {
                this.teriminalStatusText.AppendText("设置时区");
                sendStrInfo((string)InfoUtils.sendInfoTable["SQTZ"]);
                InfoUtils.sendInfoTable.Remove("SQTZ");
            }
            
            if (InfoUtils.sendInfoTable.Contains("GPRSDS"))
            {
                this.teriminalStatusText.AppendText("设置GPRS发送时间间隔");
                sendStrInfo((string)InfoUtils.sendInfoTable["GPRSDS"]);
                InfoUtils.sendInfoTable.Remove("GPRSDS");
            }
           
            if (InfoUtils.sendInfoTable.Contains("DSSJ"))
            {
                this.teriminalStatusText.AppendText("设置GPS发送时间间隔");
                sendStrInfo((string)InfoUtils.sendInfoTable["DSSJ"]);
                InfoUtils.sendInfoTable.Remove("DSSJ");
            }

            if (InfoUtils.sendInfoTable.Contains("XGMS"))
            {
                this.teriminalStatusText.AppendText("设置工作模式");
                sendStrInfo((string)InfoUtils.sendInfoTable["XGMS"]);
                InfoUtils.sendInfoTable.Remove("XGMS");
            }

            
            if (InfoUtils.sendInfoTable.Contains("ZXHM"))
            {
                this.teriminalStatusText.AppendText("设置中心号码");
                sendStrInfo((string)InfoUtils.sendInfoTable["ZXHM"]);
                InfoUtils.sendInfoTable.Remove("ZXHM");
            }

            
            if (InfoUtils.sendInfoTable.Contains("ZJHM"))
            {
                this.teriminalStatusText.AppendText("增加特定号码");
                sendStrInfo((string)InfoUtils.sendInfoTable["ZJHM"]);
                InfoUtils.sendInfoTable.Remove("ZJHM");
            }
 
            if (InfoUtils.sendInfoTable.Contains("SCHM"))
            {
                this.teriminalStatusText.AppendText("删除特定号码");
                sendStrInfo((string)InfoUtils.sendInfoTable["SCHM"]);
                InfoUtils.sendInfoTable.Remove("SCHM");
            }

            sendHexInfo("5468050123");
        }

        private void serialPortReadSet_Click(object sender, EventArgs e)
        {
            string passwd = string.Empty;
            if (InfoUtils.parTable.Contains("passwd"))
            {
                passwd = (string)InfoUtils.parTable["passwd"];
            }
            else
            {
                passwd = "000000";
            }
            sendStrInfo("CXSZ," + passwd + ",");
        }
    }
}
